var geocoder = new google.maps.Geocoder();
var southWest = new google.maps.LatLng(-54.952386,-73.081055);
var northEast = new google.maps.LatLng(-22.105999,-53.613281);
var latLngBounds = new google.maps.LatLngBounds(southWest,northEast);

$(document).ready(function () {
    $('#btn-search').click(function(e){
        if ($("#mapa-search-input").val()) {
            buscar();
            e.preventDefault()
        }
    });
    $('#mapa-search-input').bind('keypress', function(e) {
        if(e.keyCode==13){
            if ($("#mapa-search-input").val()) {
                buscar();
                e.preventDefault()
            }
        }
    });
	
    $('#mapa-search-input').autocomplete({
        source: function(request, response){
            geocoder.geocode({
                address: request.term + ' Chile',
                region: 'CL',
                bounds: latLngBounds
            }, function(results, status){
                response($.map(results, function(item){
                    return {
                        label: item.formatted_address,
                        value: item.formatted_address,
                        latitude: item.geometry.location.lat(),
                        longitude: item.geometry.location.lng()
                    }
                }));
            })
        },
        select: function(event, ui){
            var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
            appMap.map.setCenter(location);
            appMap.map.setZoom(13);
            marker = new google.maps.Marker({
                map: appMap,
                position: location
            });
        }
    });
})

/*proceso de busqueda*/
function buscar () {
    var direccion = $('#mapa-search-input').val();
    $('#mapa-search-input').val('');
    $('#mapa-search-input').autocomplete('close');
    processGeocoding(direccion, centarMapa);
}

function processGeocoding(location, callback) {
    var request = {
        language: 'es',
        region: 'CL',
        address: location + ' Chile'
    }
    geocoder.geocode(request, function(results, status) {
        if(status == google.maps.GeocoderStatus.OK) {
            centarMapa (results);
            return results;
        }
        return status;
    });
}

function centarMapa(geocodes) {
    appMap.map.setZoom(13);
    appMap.map.setCenter(geocodes[0].geometry.location);
    marker = new google.maps.Marker({
        map: appMap.map,
        position: geocodes[0].geometry.location
    });
}  